package com.waterstudio.filedownloader.ext.m3u8.client;

import android.net.Uri;
import android.support.annotation.NonNull;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by chensuilun on 2019/3/23.
 */
public class File implements Client {
    private final Uri mFilePath;
    private FileInputStream mInputStream;
    private boolean isOpen;

    public File(@NonNull Uri uri) {
        this.mFilePath = uri;
    }

    public void connect() throws IOException {
        if (isOpen) {
            return;
        }
        this.mInputStream = new FileInputStream(this.mFilePath.getPath());
        this.isOpen = true;
    }

    @Override
    public boolean isConnected() {
        return this.isOpen;
    }

    @Override
    public long getSize() throws Exception {
        long size = 0;
        if (!this.isOpen) {
            return 0;
        }
        FileInputStream fileInputStream = this.mInputStream;
        if (fileInputStream != null) {
            size = (long) fileInputStream.available();
        }
        return size;
    }

    @NonNull
    public String getUrl() {
        return this.mFilePath.toString();
    }

    public InputStream getInputStream() {
        return this.mInputStream;
    }


    @Override
    public void close() {
        try {
            if (this.mInputStream != null) {
                this.mInputStream.close();
            }
        } catch (IOException ignore) {
        } finally {
            this.isOpen = false;
            this.mInputStream = null;
        }
    }
}

